<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>图片转base64，实现本地预览</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <input type="file" name="文件" id="ipt">
  <img src="" id="preview">
</body>
<script>
  "use strict"; {
    const ipt = document.getElementById("ipt");
    const preview = document.getElementById("preview");
    ipt.onchange = e => {
      // let file = e.target.files[0];
      let file = ipt.files[0];

      // 通过读取获取，data:content/type;base64,
      const reader = new FileReader();
      reader.onload = e => {
        preview.src = e.target.result;
      };
      reader.readAsDataURL(file);
    };
  };
</script>

</html>